package io.itit.ecp.admin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.server.entity.EarlyWarningPushEntity;
import io.itit.ecp.admin.server.entity.EarlyWarningRecordEntity;
import io.itit.ecp.admin.server.entity.extend.EnergyDataExtEntity;
import io.itit.ecp.admin.server.entity.extend.UserWarningExtEntity;
import io.itit.ecp.admin.server.mapper.EarlyWarningPushMapper;
import io.itit.ecp.admin.server.service.IEarlyWarningPushService;
import io.itit.ecp.admin.server.service.IEarlyWarningRecordService;
import io.itit.grass.common.server.dto.ParamDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：预警推送服务实现类
 * @Date：Create by 2023-12-15 10:51:22
 */
@Service
public class EarlyWarningPushServiceImpl extends JoinServiceImpl<EarlyWarningPushMapper, EarlyWarningPushEntity>
        implements IEarlyWarningPushService {

    @Resource
    private IEarlyWarningRecordService earlyWarningRecordService;

    @Override
    @Transactional
    public EarlyWarningPushEntity readById(String id) {
        EarlyWarningPushEntity pushEntity = getById(id);
        if (Objects.nonNull(pushEntity)) {
            setReadProps(pushEntity);
            updateById(pushEntity);
            updateEarlyWaringRecordStatus(Collections.singleton(pushEntity.getEarlyWarningRecordId()));
        }
        return pushEntity;
    }

    @Override
    public IPage<UserWarningExtEntity> unionWarningPage(ParamDto paramDto, Page<EnergyDataExtEntity> page) {
        return getBaseMapper().unionWarningPage(paramDto,page);
    }

    @Override
    @Transactional
    public void batchRead(String userId, String type) {
        List<EarlyWarningPushEntity> list = this.lambdaQuery()
                .eq(EarlyWarningPushEntity::getUserId, userId)
                .eq(EarlyWarningPushEntity::getStatus, "1")
                .list();
        boolean hasType = StringUtils.hasLength(type);
        if (!list.isEmpty()) {
            Set<String> earlyWarningRecordIds = list.stream().map(EarlyWarningPushEntity::getEarlyWarningRecordId).collect(Collectors.toSet());
            Map<String, EarlyWarningRecordEntity> recordEntities = earlyWarningRecordIds.isEmpty() ? Collections.emptyMap() :
                    earlyWarningRecordService.listByIds(earlyWarningRecordIds).stream().collect(Collectors.toMap(EarlyWarningRecordEntity::getId, Function.identity()));
            Set<String> updateEarlyWarningRecordIds = new HashSet<>();
            for (EarlyWarningPushEntity pushEntity : list) {
                EarlyWarningRecordEntity warningRecordEntity = recordEntities.get(pushEntity.getEarlyWarningRecordId());
                if (!hasType || Objects.equals(warningRecordEntity.getWarningType(), type)) {
                    setReadProps(pushEntity);
                    updateById(pushEntity);
                    updateEarlyWarningRecordIds.add(pushEntity.getEarlyWarningRecordId());
                }
            }
            if (!updateEarlyWarningRecordIds.isEmpty()) {
                updateEarlyWaringRecordStatus(earlyWarningRecordIds);
            }
        }
    }

    private static void setReadProps(EarlyWarningPushEntity pushEntity) {
        if (!"2".equals(pushEntity.getStatus())) {
            pushEntity.setStatus("2");
        }
        if (Objects.isNull(pushEntity.getReadTime())) {
            pushEntity.setReadTime(new Date());
        }
    }

    private void updateEarlyWaringRecordStatus(Set<String> earlyWarningRecordIds) {
        for (String earlyWarningRecordId : earlyWarningRecordIds) {
            String status = "2";
            if (count(new LambdaQueryWrapper<EarlyWarningPushEntity>()
                    .eq(EarlyWarningPushEntity::getEarlyWarningRecordId, earlyWarningRecordId)
                    .eq(EarlyWarningPushEntity::getStatus, "1")
            ) == 0) {
                status = "3";
            }
            earlyWarningRecordService.lambdaUpdate()
                    .set(EarlyWarningRecordEntity::getStatus, status)
                    .eq(EarlyWarningRecordEntity::getId, earlyWarningRecordId);
        }
    }
}